#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
=================================================
# @File    : report_analysis
# @IDE     : PyCharm
# @Author  : liuxiangui
# @Date    : 2023/12/30 14:54
# @Describe: 
==================================================
'''
import json
import os
from typing import Text
from library.tools.file_tool.setting import root_path, get_all_files
from library.tools.time import timestamp_to_datatime, sub_timestamp_to_datetime

class ReportAnalysis:
    """统计分析用例执行质量"""

    @classmethod
    def get_case_count(cls) -> dict:
        try:
            file_name = os.path.join(root_path(), "report/html/widgets/summary.json")
            with open(file_name, 'r', encoding='utf-8') as file:
                data = json.load(file)
            _caseCount = data['statistic']
            _time = data['time']
            keep_keys = {"passed", "failed", "broken", "skipped", "total"}
            run_case_data = {k: v for k, v in data['statistic'].items() if k in keep_keys}
            # 判断运行用例总数大于0
            if _caseCount["total"] > 0:
                # 计算用例成功率
                run_case_data["pass_rate"] = round(
                    (_caseCount["passed"] + _caseCount["skipped"]) / _caseCount["total"] * 100, 2
                )
            else:
                # 如果未运行用例，则成功率为 0.0
                run_case_data["pass_rate"] = 0.0
            # 收集用例运行时长
            run_case_data['time'] = "" if run_case_data['total'] == 0 else sub_timestamp_to_datetime(
                data["time"]["duration"])
            run_case_data['starttime'] = timestamp_to_datatime(data["time"]["start"])
            run_case_data['endtime'] = timestamp_to_datatime(data["time"]["stop"])
            return run_case_data
        except FileNotFoundError as exc:
            raise FileNotFoundError("检查是否生成allure报告！！")

    @classmethod
    def get_failed_case_detail(cls) -> Text:
        """获取失败用例名称和路径"""
        # 将所有数据都收集到files中
        files = []
        jsonfiles = get_all_files(os.path.join(root_path(), "report/html/data/test-cases"), ".json")
        for i in jsonfiles:
            with open(i, 'r', encoding='utf-8') as file:
                date = json.load(file)
                files.append(date)
        # 失败用例的名称和代码路径
        errorCase = []
        for i in files:
            if i['status'] == 'failed' or i['status'] == 'broken':
                errorCase.append((i['name'], i['fullName']))
        # 失败用例名称路径处理成为文本
        values = ""
        if len(errorCase) >= 1:
            values = "[失败用例详情]:\n"
            values += "\t******************************\n"
            for i in errorCase:
                values += "\t" + i[0] + ":" + i[1] + "\n"
            values += "\t******************************"
        return values


if __name__ == '__main__':
    ...
